import React, { useState, useEffect } from "react";
import { Layout, Tabs, ConfigProvider } from "antd";
import FilterBar from "./components/FilterBar";
import DataTable from "./components/DataTable";
import { fetchReportData, exportToExcel } from "./service";
import { WeeklyReportItem, WeeklyReportQueryParams } from "./types";
import "./index.less";

const { Content } = Layout;
const { TabPane } = Tabs;

const Pg2: React.FC = () => {
  const [activeTab, setActiveTab] = useState("3");
  const [loading, setLoading] = useState<boolean>(false);
  const [tableData, setTableData] = useState<WeeklyReportItem[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState<WeeklyReportQueryParams>({
    dateRange: "2025-04-28 ~ 2025-05-04",
    projectId: "",
    teamName: "",
    confirmDate: "",
    planDate: "",
    manager: "",
  });

  useEffect(() => {
    fetchTableData();
  }, [pagination.current, pagination.pageSize]);

  const fetchTableData = async () => {
    try {
      setLoading(true);
      // 构造查询参数
      const params: WeeklyReportQueryParams = {
        ...searchParams,
        page: pagination.current,
        pageSize: pagination.pageSize,
      };

      const res = await fetchReportData(params);
      setTableData(res.list || []);
      setTotal(res.total || 0);
    } catch (error) {
      console.error("获取数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
  };

  const handleSearch = (values: WeeklyReportQueryParams) => {
    setSearchParams(values);
    setPagination({ ...pagination, current: 1 });
    fetchTableData();
  };

  const handlePageChange = (page: number, pageSize: number) => {
    setPagination({ current: page, pageSize });
  };

  // 处理导出Excel
  const handleExport = () => {
    exportToExcel(searchParams);
  };

  return (
    <Layout className="pg2-layout">
      <Content className="pg2-content">
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          className="pg2-tabs"
        >
          <TabPane tab="上线日历表" key="1" />
          <TabPane tab="T+2报表" key="2" />
          <TabPane tab="上线周报表" key="3" />
          <TabPane tab="卡中心上线报表" key="4" />
          <TabPane tab="Label策略管理" key="5" />
          <TabPane tab="重要业务系统投产规划(中心)" key="6" />
          <TabPane tab="重要业务系统投产规划(我的)" key="7" />
        </Tabs>
        
        <div className="pg2-container">
          <FilterBar 
            initialValues={searchParams} 
            onSearch={handleSearch} 
          />
          
          <DataTable 
            loading={loading}
            dataSource={tableData}
            total={total}
            pagination={pagination}
            onChange={handlePageChange}
          />
        </div>
      </Content>
    </Layout>
  );
};

export default Pg2;
